#include "form.h"
#include "ui_form.h"
#include <QDebug>
#include <QDropEvent>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QMessageBox>
#include <QPainter>
#include <QScreen>
#include <QGuiApplication>
Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form)
{
    ui->setupUi(this);
    this->setAcceptDrops(true); //必须设置，不然无法接收拖放事件
}

Form::~Form()
{
    delete ui;
}

void Form::dragEnterEvent(QDragEnterEvent *event)
{
    qDebug()<<"dragEnterEvent";
    if(event->mimeData()->hasUrls())
    {
        event->acceptProposedAction(); //事件数据中存在路径，方向事件, 不接收的话dropEvent事件不会触发
        qDebug()<<"dragEnterEvent"<<event->mimeData()->urls();
    }
    else
    {
        event->ignore();//表示不要这类事件，继续往其他部件传递
    }
}

void Form::dragMoveEvent(QDragMoveEvent *event)
{
    qDebug()<<"dragMoveEvent";
}

void Form::dropEvent(QDropEvent *event)
{
    qDebug()<<"dropEvent";
    const QMimeData *mimeData = event->mimeData();
    if(mimeData->hasUrls())
    {
        QList<QUrl> urls = mimeData->urls();
        QString fileName = urls.at(0).toLocalFile();
        int index=fileName.lastIndexOf(".");
        QString Suffix=fileName.mid(index,-1);
        qDebug()<<"PATH"<<fileName<<Suffix;
        if(Suffix.indexOf("png",Qt::CaseInsensitive)!=-1
                ||Suffix.indexOf("jpg",Qt::CaseInsensitive)==-1
                ||Suffix.indexOf("jpeg",Qt::CaseInsensitive)!=-1
                ||Suffix.indexOf("bmp",Qt::CaseInsensitive)!=-1
                )
        {
            m_DataList.append(fileName);
            m_data=qvariant_cast<QImage>(mimeData->imageData());
            update();
        }else
        {
            QMessageBox::critical(NULL,QString("警告!"),QString("无法完成请求，因为它不是所指类型文档！"),QString("确定"));
        }
    }
//    QString Path;
//    QScreen *screen = QGuiApplication::primaryScreen();
//    screen->grabWindow(this->winId()).save(Path);
}

void Form::dragLeaveEvent(QDragLeaveEvent *event)
{
    qDebug()<<"dragLeaveEvent";
}

void Form::paintEvent(QPaintEvent *event)
{
    if(m_DataList.count()>0)
    {
        QPainter painter(this);
        QImage image(m_DataList.at(0));
        painter.drawImage(this->rect(),image);

//        QPixmap map(m_DataList.at(0));
//        painter.drawPixmap(this->rect(),map);
        qDebug()<<"paintEvent";
    }
    else
    {
        QWidget::paintEvent(event);
    }

}
